import React, { useEffect, useState } from "react";
import { View, Text, ScrollView, Image } from "@tarojs/components";
import { useRouter } from "@tarojs/taro";
import { setToken, getToken } from "../../utils/cookies";
import { getImageList, deleteImage } from "../../api/image";
import { FileInfo } from "../../types/Images";
import { showLoading, hideLoading } from "@tarojs/taro";
import { Button, ImagePreview, Uploader, Dialog } from "@nutui/nutui-react-taro";
import { Close } from '@nutui/icons-react-taro'
import './index.less'
const prefix = 'my-album'
const Index = () => {
  const [fileList, setFileList] = React.useState<FileInfo[]>([]);
  const router = useRouter();
  const [isLoading, setIsLoading] = React.useState(false);
  const { db_man } = router.params;
  const [showPreview, setShowPreview] = useState(false)
  const [previewImage, setPreviewImage] = useState<Array<{ src: string }>>([])
  const [init, setInit] = useState<any>(null)
  const [editVisible, setEditVisible] = useState(false) // 编辑控制
  const [pageParams, setPageParams] = React.useState({
    pageSize: 30,
    pageNum: 1,
    total: 0
  })
  const fetchList = async () => {
    showLoading({
      title: '加载中...',
      mask: true // 防止触摸穿透
    })
    try {
      let { data, success } = await getImageList({ ...pageParams })
      if (success) {
        let handleData = fileList.concat(data.list)
        let handleDataPreview = handleData.map((item) => { return { src: item.url } })
        setFileList(handleData)
        setPreviewImage(handleDataPreview)
        setPageParams({ ...pageParams, total: data.total, pageNum: data.pageNum, pageSize: data.pageSize })
        console.log(data)
      }
    } catch (error) {

    } finally {
      hideLoading()
    }
  }
  if (db_man) {
    setToken('db_man', db_man)
  }
  const handleScrollToLower = () => {
    // if (!isLoading && fileList.length < pageParams.total) {
    //   setPageParams(prev => ({...prev, pageNum: prev.pageNum + 1}));
    // }
    if (!isLoading && fileList.length < pageParams.total) {
      setPageParams(prev => ({ ...prev, pageNum: prev.pageNum + 1 }));
    } else {
      setIsLoading(true)
    }
    console.log('执行了哦')
  }
  useEffect(() => {
    fetchList()

  }, [pageParams.pageNum])
  return (
    <View className={`${prefix}`}>
      <View className={`${prefix}-header`}>
        <View className={`${prefix}-title`}>
          <Text>我的相册</Text>
          <Uploader url={'https://dbyxs.xyz/img'} headers={{
            // cookie: getToken(),
            Authorization: 'Bearer ' + getToken(),
          }} multiple maxCount="3" onFailure={() => {
            hideLoading()
          }} onSuccess={(e) => {
            let { responseText } = e
            let { prdUrl } = JSON.parse(responseText).data
            let handleData = fileList.concat([{ url: prdUrl }])
            setFileList(handleData)
            console.log(prdUrl)
            // console.log(JSON.parse(responseText))
          }}
            onDelete={(e) => {
              console.log(e)
              // setFileValue([])
              hideLoading()
            }}
            onChange={(e) => {

            }} >
            <Button style={{ marginLeft: '20px' }} className={`${prefix}-btn`} type="success" size="small">
              上传文件
            </Button>
          </Uploader>
          <Button onClick={() => {
            setEditVisible(!editVisible)
          }} style={{ marginLeft: '20px' }} className={`${prefix}-btn`} type="primary" size="small">
            {editVisible ? '取消编辑' : '编辑'}
          </Button>
        </View>
      </View>
      <View className={`${prefix}-main`}>
        <ScrollView
          scrollY
          style={{ height: 'calc(100vh - 0px)' }}  // Add height constraint
          enableBackToTop
          onScrollToLower={handleScrollToLower}
          lowerThreshold={100}
          className={`${prefix}-scroll`}>
          <View className={`${prefix}-list`}>
            {fileList.map((item, index) => {
              return <View key={index} style={{ width: '31%', height: '100px', marginBottom: '15px', position: 'relative' }}>
                {editVisible && <Close onClick={() => {
                  Dialog.open('test', {
                    title: '确认删除',
                    content: '删除后将无法恢复哦！',
                    onConfirm: async () => {
                      showLoading()
                      try {
                        let { success } = await deleteImage({ imageId: item.id as number })
                      } catch (error) {

                      } finally {
                        hideLoading()
                      }
                      let handleData = fileList.filter((it) => it.id !== item.id)
                      setFileList(handleData)
                      Dialog.close('test')
                    },
                    onCancel: () => {
                      Dialog.close('test')
                    },
                  })
                }} color="#888" className={`${prefix}-icon`}></Close>}
                <Image lazyLoad
                  onClick={() => {
                    setShowPreview(true)
                    setInit(index + 1)
                  }}
                  // lazyThreshold={200}
                  mode="aspectFill" src={item.url} key={index} className={`${prefix}-img`}></Image>
              </View>
            })}
          </View>
          <View className={`${prefix}-loading`}>
            {isLoading && <Text className="loading-text">没有更多了...</Text>}
          </View>
        </ScrollView>

      </View>
      <Dialog id="test" />
      <ImagePreview
        defaultValue={init}
        autoPlay
        images={previewImage}
        visible={showPreview}
        onClose={() => setShowPreview(false)}
      />
    </View>
  )
}
export default Index